module Wikiloc
  class InfoGetter
    def initialize(location, data_type)
      @location, @data_type = location, data_type
    end

    def page_url
      'http://en.wikipedia.org/wiki/'
    end

    def get_info
      case @data_type.downcase
      #when 'link'
      #  'http://en.wikipedia.org/wiki/' + @location
      when 'capital'
        find_data_in_table 'Capital'
      when 'currency'
        find_data_in_table 'Currency'
      when 'language'
        find_data_in_table 'Official language'
      else
        :invalid
      end
    end

    def agent
      @agent ||= Mechanize.new.tap { |agent| agent.user_agent_alias = 'Mac Safari' }
    end

    def find_data_in_table(datatype)
      key_row = page.parser.xpath("//tr[contains(.,'#{datatype}')]").first
      cut_number_off key_row.children[2].children.first.text
    end

    def page
      @page ||= agent.get(page_url + @location)
    end

    def cut_number_off(data)
      data.gsub /[0-9]+.*/, ""
    end

  end
end
